<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container justify-between">
      <div>
        <!--<el-switch v-model="multi" inactive-text="批量操作"></el-switch>-->
        <!--<template v-if="multi">-->
        <!--<el-button size="mini" type="danger" @click="doRemove('','确定要删除吗？')">删除</el-button>-->
        <!--</template>-->
      </div>
      <div>
        <el-input @keyup.enter.native="doSearch" style="width: 200px;" class="filter-item" placeholder="输入名称搜索"
                  v-model="listQuery.keyword">
        </el-input>
        <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="doSearch">搜索
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus"
                   @click="openEditor()">
          新增活动
        </el-button>
      </div>
    </div>
    <div class="hongbao_content">
      <div class="hongbao_list">
        <div class="hongbao_wrap" id="add_hongbao">
          <div class="money">
            当前余额<span class='money_text' >{{balance_money}}</span>元
            <el-button class="filter-item" size="mini" type="primary" id='do_charge' @click="goCharge">去充值</el-button>
          </div>
          <div class="img_wrap"  @click="openEditor()">
            <img src="../../assets/images/tianjia.png" alt="">
          </div>
          <div class='first_tips'>转发职位领红包</div>
          <div class="guize">
            <div class="guize_title">【红包规则】</div>
            <div class="guize_line">1. 发布红包活动，在红包页面输入金额，数量和有效期，确定支付即配置成功；</div>
            <div class="guize_line">2. 在微信朋友圈或聊天分享红包活动，所有传播者均可领取红包；</div>
            <div class="guize_line">3. 单个岗位每人每天可以领取一次红包，直到活动结束（红包金额被领完或者到达截止时间）；</div>
            <div class="guize_line">4. 如果删除活动或者红包活动时间截止，活动剩余金额即返回账户余额。</div>
          </div>
        </div>
        <div class="hongbao_wrap" v-for="item in list">
          <div class="status">
            <span class='on_time' v-if="item.status==1">正在进行中</span>
            <span class='off_time' v-else>已过期</span>
          </div>
          <div class="title">
            {{item.title}}
          </div>
          <div class="time">
            活动时间：{{item.start_time}} —— {{item.end_time}}
          </div>
          <div class="hongbao_type">
            红包类型： 转发红包
          </div>
          <div class="job_wrap">
            <div class="job_title">活动岗位</div>
            <div class="job_list">
              <span v-for="job_item in item.job_list">{{job_item}}</span>
            </div>
          </div>
          <div class="money">
            <div class="tips">
              剩余/总金额
            </div>
            <div class="line_circle">
              <div class="sur_line" :style='{width:item.balance_rate}'></div>
              <div class="money_text">
                {{item.balance_price}} / {{item.total_price}}
              </div>
            </div>
          </div>
          <div class="btn-wrap">
            <el-button type="info" @click="downloadExcel(item.id)">数据报表</el-button>
            <el-button type="warning" v-if="item.status==1" @click="openEditor(item.id)">修改活动</el-button>
            <el-button type="danger" @click="doRemove(item.id,'确定要删除【'+item.title+'】吗？')">删除活动</el-button>
          </div>
        </div>
      </div>
    </div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogJobFormVisible">
      <div class="title" style="font-size:16px;line-height:2em;text-align:center;font-weight:bold;color:#1296db;">选择岗位</div>
      <div class="top-wrap">
        <el-tag  v-for="item in bean.job_list" :key="item.name" closable style="margin-left:6px;" @close="deleteJob(item.id)">
          {{item.name}}
        </el-tag>
      </div>
      <div class="job_list">
        <el-table ref="multipleTable" :data="job_list" style="width: 100%" height="300" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column align="left" label="岗位名称">
            <template slot-scope="scope">
              <span>{{scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column align="left" label="所属单位" prop="dept_id" :filters="dept_list" :filter-method="filterDept"
                           filter-placement="bottom-end">
            <template slot-scope="scope">
              <span>{{scope.row.dept_name }}</span>
            </template>
          </el-table-column>
          <el-table-column align="left" label="所在城市" prop="address_city" :filters="city_list" :filter-method="filterCity"
                           filter-placement="bottom-end">
            <template slot-scope="scope">
              <span>{{scope.row.address_city }}</span>
            </template>
          </el-table-column>
          <el-table-column align="left" label="登记表单" :filters="form_list" :prop="form_type"
                           :filter-method="filterForm"
                           filter-placement="bottom-end">
            <template slot-scope="scope">
              <span v-if="scope.row.ext_info_obj&&scope.row.ext_info_obj.template_id">{{scope.row.ext_info_obj.template_id | show_basedatas('template_id')}}</span>
              <span v-else="scope.row.ext_info_obj&&scope.row.ext_info_obj.job_type">{{scope.row.ext_info_obj.job_type | show_basedatas('job_type')}}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="goNextStep" :loading="dealing">下一步</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <div class="title" style="font-size:16px;line-height:2em;text-align:center;font-weight:bold;color:#1296db;">红包配置</div>
      <el-form :rules="formRules" ref="dataForm" :model="bean" label-position="right" label-width="120px"
               style='width: 400px; margin-left:50px;margin-top:20px;'>
        <template>
          <el-form-item label="活动名称" prop="title">
            <el-input v-model="bean.title" placeholder="输入活动名称"></el-input>
          </el-form-item>
          <el-form-item label="红包金额" prop="total_price">
            <el-input v-model="bean.total_price" placeholder="输入红包金额" :disabled="!!bean.id"></el-input>
            <span>当前余额<span class='money_text' >{{balance_money}}</span>元</span>
          </el-form-item>
          <el-form-item label="红包个数" prop="amount">
            <el-input v-model="bean.amount" placeholder="输入红包个数" :disabled="!!bean.id"></el-input>
          </el-form-item>
          <el-form-item label="分配方式" prop="type">
            <el-radio v-model="bean.type" label="1" :disabled="!!bean.id">随机</el-radio>
            <el-radio v-model="bean.type" label="2" :disabled="!!bean.id">平均</el-radio>
          </el-form-item>
          <el-form-item label="开始时间" prop="start_time">
            <el-date-picker style="width:280px;" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
              v-model="bean.start_time"
              type="datetime"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="end_time">
            <el-date-picker style="width:280px;" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
              v-model="bean.end_time"
              type="datetime"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveBean" :loading="dealing">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
  import Vue from 'vue'
  import waves from '@/directive/waves' // 水波纹指令
  import API from '@/api'
  import Http from '@/http'
  import Store from '@/store'
  import Msg from '@/utils/msg'
  import Utils from '@/utils/common'
  import _ from 'underscore'
  import Qiniu from '@/utils/qiniu'
  import {mapGetters} from 'vuex'


  export default {
    directives: {waves},
    data() {
      return {
        dialogJobFormVisible:false,
        dealing: false,
//				multi: false,
        job_list:[],
        dept_list:[],
        city_list:[],
        form_list:[],
        company:Store.getters.user.company,
        list: [],
        listQuery:{
          keyword:''
        },
        balance_money:0,
        bean: {
          job_list:[],
        },
        form_type:'',
        dialogTitle: '',
        dialogFormVisible: false,
        formRules: {
          title: [{required: true, message: '请填写活动名称', trigger: 'blur'}],
          total_price: [{required: true, message: '请填写红包金额', trigger: 'blur'}],
          amount: [{required: true, message: '请填写红包个数', trigger: 'blur'}],
          type: [{required: true, message: '请选择分配方式', trigger: 'blur'}],
          start_time: [{required: true, message: '请选择开始时间', trigger: 'blur'}],
          end_time: [{required: true, message: '请选择结束时间', trigger: 'blur'}],
        },
      }
    },
    filters: {},
    components: {},
    created() {
      this.loadList()
      this.loadBalance()
      this.loadJobList()
      if(this.company.template){
        this.job_type_list = Store.getters.basedata.job_type
        var form_list = []
        job_type_list.forEach(function(item){
          form_list.push({text:item.data_text,value:item.data_value})
        })
        this.form_list = form_list
        this.form_type = 'job_type'
      }else{
        var template_list = Store.getters.basedata.template_id
        var form_list = []
        template_list.forEach(function(item){
          form_list.push({text:item.data_text,value:item.data_value})
        })
        this.form_list = form_list
        this.form_type = 'template_id'
      }
    },
    computed: {},
    methods: {
      filterForm(value, row){
        return row.ext_info_obj[this.form_type] === value;
      },
      filterCity(value, row){
        return row.address_city === value;
      },
      filterDept(value, row){
        return row.dept_id === value;
      },
      handleSelectionChange(val) {
        var job_list = val
        this.bean.job_list=[];
        job_list.forEach((item)=>{
          this.bean.job_list.push(item)
        })
      },
      deleteJob(id){
        var row = {}
        for(var i=0;i<this.job_list.length;i++){
          if(this.job_list[i].id==id){
            row = this.job_list[i]
          }
        }
        if( this.$refs.multipleTable){
          this.$refs.multipleTable.toggleRowSelection(row);
        }
      },
      loadJobList(){
        Http.getModel(API.getWechatJobList, {}, false).then((json) => {
          this.loading = false
          if (json.code == 0) {
            var list =  json.data
            var city_text_list = [];
            var dept_list = []
            for(var i=0;i<list.length;i++){
              list[i].ext_info_obj = JSON.parse(list[i].ext_info)
              list[i].checked = false
              if(city_text_list.indexOf(list[i].address_city)==-1&&list[i].address_city){
                city_text_list.push(list[i].address_city)
              }
              dept_list.push({value:list[i].dept_id,text:list[i].dept_name})
            }
            var result = [];
            var obj = {};
            for(var i =0; i<dept_list.length; i++){
              if(!obj[dept_list[i].value]){
                result.push(dept_list[i]);
                obj[dept_list[i].value] = true;
              }
            }
            this.job_list = list;
            this.dept_list = result;
            var city_list = [];
            for(var j=0;j<city_text_list.length;j++){
              city_list.push({value:city_text_list[j],text:city_text_list[j]})
            }
            this.city_list = city_list
          }
        })
      },
      loadList() {
        Http.getModel(API.redPackageList, this.listQuery, false).then((json) => {
          this.loading = false
          if (json.code == 0) {
            var list = json.data
            for (var i = 0; i < list.length; i++) {
              list[i].job_list = list[i].job_name.split(",")
              list[i].balance_rate = Number(list[i].balance_price / list[i].total_price * 100);
            }
            if (list.length == 0) {
              list = []
            }
            this.list = list
          }
        })
      },
      loadBalance() {
        Http.getModel(API.SmsNum, {}, false).then((json) => {
          if (json.code == 0) {
            this.balance_money = json.data.balance

          }
        })
      },
      goCharge(){
        this.$router.push({path: '../setting/account'})
      },
      downloadExcel(id){
        var DownLoadFile = function (options) {
          var config = $.extend(true, { method: 'post' }, options);
          var $iframe = $('<iframe id="down-file-iframe" />');
          var $form = $('<form target="down-file-iframe" method="' + config.method + '" />');
          $form.attr('action', config.url);
          for (var key in config.data) {
            $form.append('<input type="hidden" name="' + key + '" value="' + config.data[key] + '" />');
          }
          $iframe.append($form);
          $(document.body).append($iframe);
          $form[0].submit();
          $iframe.remove();
        }
        var params = {
          url:window.server_root+API.downRedPackageData,
          data:{
            id:id,
          }
        }
        DownLoadFile(params)
      },
      openEditor(id) {
        if (id) {
          this.dialogFormVisible = true
          this.loadBean(id)
          this.dialogTitle = '编辑红包活动'
        } else {
          this.dialogJobFormVisible = true
          this.dialogTitle = '新增红包活动'
          if( this.$refs.multipleTable){
            this.$refs.multipleTable.clearSelection();
          }
          this.bean = {
            job_list:[]
          }
        }

      },
      goNextStep(){
        if(this.bean.job_list.length==0){
          Msg.error("请先选择岗位！")
          return false
        }
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      loadBean(id) {
        Http.getModel(API.redPackageDetail, {id: id}).then((json) => {
          if (json.code == 0) {
            let bean = json.data
//            bean.start_time = Date(bean.start_time)
//            bean.end_time = Date(bean.end_time)
            this.bean = bean
          }
        })
      },
      saveBean() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.dealing = true
            if(this.bean.id){
              var bean = this.bean
              var params = {
                title:bean.title,
                start_time:bean.start_time,
                end_time:bean.end_time,
                id:bean.id
              }
              Http.getModel(API.editRedPackage, params, false).then((json) => {
                this.dealing = false
                if (json.code == 0) {
                  this.dialogFormVisible = false
                  Msg.success(json.msg, () => {
                    this.loadList()
                  })
                } else {
                  Msg.error(json.msg)
                }
              })
            }else{
              var params = this.bean
              var job_id_list = []
              for(var i=0;i<this.bean.job_list.length;i++){
                job_id_list.push(this.bean.job_list[i].id)
              }
              params.job_id =job_id_list.join()
              delete params.job_list
              params.trigger_type = 1
              Http.getModel(API.addRedPackageOption, params, false).then((json) => {
                this.dealing = false
                if (json.code == 0) {
                  this.dialogFormVisible = false
                  this.dialogJobFormVisible = false
                  this.$refs.multipleTable.clearSelection();
                  Msg.success(json.msg, () => {
                    this.loadList()
                  })
                } else {
                  Msg.error(json.msg)
                }
              })
            }

          }
        })
      } ,
      doRemove(ids, tips) {
        if (!ids) {
          if (this.multipleSelection.length == 0) {
            Msg.error("请先选择");
            return false;
          } else {
            ids = _.pluck(this.multipleSelection, "id").join(",");
          }
        }
        Msg.confirm(tips, () => {
          Http.getModel(API.delActivity, {id: ids}, false).then((json) => {
            if (json.code == 0) {
              Msg.success(json.msg, () => {
                this.loadList()
              })
            } else {
              Msg.error(json.msg)
            }
          })
        })
      } ,
      /***   公用部分 start ***/
      onSelectionChange(val) {
        this.multipleSelection = val;
      }
      ,
      doSearch() {
        this.listQuery.page = 1
        this.loadList()
      }
      ,
      onSizeChange(val) {
        this.listQuery.pageSize = val
        this.loadList()
      }
      ,
      onCurrentChange(val) {
        this.listQuery.pageNumber = val
        this.loadList()
      }
      ,
      /***   公用部分 end ***/
    }
  }
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
  .top-wrap{
    border:1px solid #333;
    min-height:90px;
    padding:20px;
  }
  .hongbao_content {
    padding: 50px;
  }

  .hongbao_list {
    display: flex;
    flex-wrap: wrap;

  }

  #add_hongbao {
    cursor: pointer;
  }

  #add_hongbao .money {
    font-size: 12px;
    line-height: 1.6;
    text-align: right;
    position: relative;
    right: -20px;
  }
  .money_text {
    color: #ff0000;
    margin: 0 4px;
    font-weight: bold;
  }
  #add_hongbao .money .money_text {
    color: #ff0000;
    margin: 0 4px;
    font-weight: bold;
  }
  .hongbao_list .hongbao_wrap {
    width: 400px;
    height: 550px;
    bakcground: #fff;
    margin-right: 66px;
    margin-bottom: 66px;
    border: 2px dashed #abb4c3;
    line-height: 1.5;
    padding: 0 40px;
    box-sizing: border-box;
  }

  .hongbao_list .img_wrap {
    padding-top: 80px;
  }

  .hongbao_list .img_wrap img {
    width: 72px;
    height: 72px;
    display: block;
    margin: 0 auto;
  }

  .hongbao_list .first_tips {
    margin-top: 45px;
    text-align: center;
    color: #abb4c3;
    font-size: 13px;
    line-height: 1em;
  }

  .hongbao_list .guize {
    margin-top: 45px;
    color: #abb4c3;
    font-size: 13px;
  }

  .hongbao_list .guize .guize_title {
    font-weight: bold;
  }

  .hongbao_list .guize .guize_line {
    text-indent: 2em;
    line-height: 1.5;
  }

  .hongbao_wrap .status {
    line-height: 60px;
    border-bottom: 1px dashed #f2f2f2;
    text-align: center;
    font-size: 24px;
    font-weight: bold;
  }

  .hongbao_wrap .status .on_time {
    color: #1296db;
  }

  .hongbao_wrap .status .off_time {
    color: #eaeaea;
  }

  .hongbao_wrap .title {
    margin-top: 20px;
    font-size: 24px;
    color: #333;
    font-weight: bold;
    line-hieght: 1.2;
  }

  .hongbao_wrap .time {
    color: #ccc;
    font-size: 12px;
  }

  .hongbao_wrap .hongbao_type {
    font-size: 12px;
  }

  .hongbao_wrap .job_wrap .job_title {
    font-size: 16px;
    line-height: 3;
    text-align: center;
    font-weight: bold;
  }

  .hongbao_wrap .job_wrap .job_list {
    height: 160px;
    overflow-y: auto;
  }

  .hongbao_wrap .job_wrap .job_list span {
    display: inline-block;
    background: #8DBBFB;
    color: #fff;
    height: 28px;
    line-height: 28px;
    font-size: 14px;
    padding: 0 15px;
    margin: 0 8px 8px 0;
  }

  .hongbao_wrap .money {
    margin-top: 20px;
  }

  .hongbao_wrap .money .tips {
    text-align: center;
  }

  .hongbao_wrap .money .line_circle {
    margin-top: 8px;
    position: relative;
    height: 30px;
    border-radius: 15px;
    border: 2px solid #FFD060;
    overflow: hidden;
  }

  .hongbao_wrap .money .line_circle .sur_line {
    background: #FFD060;
    height: 30px;
  }

  .hongbao_wrap .money .line_circle .money_text {
    color: #787878;
    position: absolute;
    top: 0;
    left: 10px;
    height: 30px;
    line-height: 30px;
    font-size: 12px;
  }

  .hongbao_wrap .btn-wrap {
    margin-top: 30px;
    display: flex;
    justify-content: space-around;
  }


</style>
